package com.youzi.tunnel.client.work;

import com.alibaba.fastjson.JSONObject;
import com.youzi.tunnel.client.config.ClientProperties;
import com.youzi.tunnel.client.entity.Client;
import com.youzi.tunnel.client.handlers.ClientChannelHandler;
import com.youzi.tunnel.client.handlers.IdleHeartbeatHandler;
import com.youzi.tunnel.common.protocol.*;
import com.youzi.tunnel.common.utils.MacUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.ssl.SslHandler;
import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

/**
 * 客户端启动器
 */
@Slf4j
public class ClientStarter {

    public static void start() {
        log.info("启动中...");
        String clientId = ClientProperties.getInstance().getClientId();
        InetSocketAddress inetAddress = new InetSocketAddress(ClientProperties.getInstance().getServerHost(), ClientProperties.getInstance().getServerPort());

        Bootstrap bootstrap = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {

                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        if (ClientProperties.getInstance().isSslEnable()) {
                            SSLContext sslContext = SslContextCreator.getSSLContext();
                            SSLEngine sslEngine = sslContext.createSSLEngine();
                            sslEngine.setUseClientMode(true);

                            ch.pipeline().addLast(new SslHandler(sslEngine));
                        }
                        ch.pipeline().addLast(new MessageDecoder());
                        ch.pipeline().addLast(new MessageEncoder());
                        ch.pipeline().addLast(new IdleHeartbeatHandler());
                        ch.pipeline().addLast(new ClientChannelHandler());

                    }
                });
        //连接服务器
        bootstrap.connect(inetAddress).addListener((ChannelFutureListener) future -> {
            Channel channel = future.channel();
            //记录客户端id, 链路关闭时用, 获取时为空则说明是隧道链路, 否则为客户端链路
            channel.attr(Constants.CLIENT_ID).set(clientId);

            // 连接后端服务器成功
            if (future.isSuccess()) {
                log.info("连接成功!");
                //认证
                Message message = new Message();
                message.setType(Message.TYPE.LINK);

                String macAddress = MacUtil.getCurrentIpLocalMac();

                message.setData(JSONObject.toJSONString(new Client(clientId, macAddress)).getBytes(StandardCharsets.UTF_8));
                channel.writeAndFlush(message);
                log.info("认证消息发送完成!");
            } else {
                log.error("连接失败!");
                channel.close().sync();
                System.exit(2);
            }
        });
    }
}
